package cn.ieayinfo.train.mybooks.Web;

import cn.ieayinfo.train.mybooks.Entity.Book;
import cn.ieayinfo.train.mybooks.Entity.User;
import cn.ieayinfo.train.mybooks.Service.BookService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Date;

@Controller
@RequestMapping("/books")
public class BookController {
    @Resource
    BookService bookService;

    @RequestMapping("")
    public String books(ModelMap model) {
        //获取当前登录人的书单列表
        User currentUser  = (User) SecurityUtils.getSubject().getPrincipal();
        model.put("books", bookService.getBookListByUid(currentUser.getUid()));
        return "books";
    }
    @RequestMapping("add")
    public String toAdd() {
        return "add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(Book book) {
        if(book.getId() == null) { // 新增时加入默认值
            User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
            book.setCreatoruid(currentUser.getUid());
            book.setCreatetime(new Date());
        }
        bookService.save(book);
        return "redirect:/books";
    }
    @RequestMapping("edit/{id}")
    public String toEdit(@PathVariable Long id, ModelMap model) {
        Book book = bookService.findBookById(id);
        if(book == null) {
            model.put("msg", "不存在此图书");
        } else {
            model.put("book", book);
        }
        return "add";
    }

    @RequestMapping("removal/{id}")
    public String toDel(@PathVariable Long id, ModelMap model) {
        Book book = bookService.findBookById(id);
        if(book == null) {
            model.put("msg", "不存在此图书");
        } else {
            bookService.deleteById(id);
        }
        return "redirect:/books";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
